package com.snail.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
//幂等性工具（基于 Redis）
public class IdempotentUtil {
    private final StringRedisTemplate redisTemplate;

    public IdempotentUtil(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 检查并设置幂等键（30分钟过期）
    public boolean checkAndSet(String key) {
        Boolean success = redisTemplate.opsForValue().setIfAbsent(
                "idempotent:" + key,
                "1",
                30,
                TimeUnit.MINUTES
        );
        return Boolean.TRUE.equals(success);
    }

    // 删除幂等键（如订单创建失败时）
    public void delete(String key) {
        redisTemplate.delete("idempotent:" + key);
    }
}